package com.saihai.framework.web.service;

import com.saihai.common.constant.CacheConstants;
import com.saihai.common.constant.Constants;
import com.saihai.common.constant.JianKangConstant;
import com.saihai.common.constant.UserConstants;
import com.saihai.common.core.domain.entity.SysUser;
import com.saihai.common.core.domain.model.LoginUser;
import com.saihai.common.core.domain.model.WxUser;
import com.saihai.common.core.redis.RedisCache;
import com.saihai.common.exception.ServiceException;
import com.saihai.common.exception.user.*;
import com.saihai.common.utils.DateUtils;
import com.saihai.common.utils.MessageUtils;
import com.saihai.common.utils.StringUtils;
import com.saihai.common.utils.ip.IpUtils;
import com.saihai.framework.manager.AsyncManager;
import com.saihai.framework.manager.factory.AsyncFactory;
import com.saihai.framework.security.context.AuthenticationContextHolder;
import com.saihai.jiankang.ufAppMenu.domain.UfAppMenu;
import com.saihai.jiankang.ufAppMenu.service.IUfAppMenuService;
import com.saihai.jiankang.ufJsgl.domain.UfJsgl;
import com.saihai.jiankang.ufJsgl.service.IUfJsglService;
import com.saihai.jiankang.ufJzg.domain.UfJzg;
import com.saihai.jiankang.ufJzg.service.IUfJzgService;
import com.saihai.jiankang.ufYsgl.domain.UfYsgl;
import com.saihai.jiankang.ufYsgl.service.IUfYsglService;
import com.saihai.jiankang.ufZhgl.domain.UfZhgl;
import com.saihai.jiankang.ufZhgl.service.IUfZhglService;
import com.saihai.system.service.ISysConfigService;
import com.saihai.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IUfYsglService ufYsglService;

    @Autowired
    private IUfZhglService ufZhglService;

    @Autowired
    private IUfJsglService ufJsglService;

    @Autowired
    private IUfAppMenuService ufAppMenuService;

    @Autowired
    private IUfJzgService ufJzgService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
//        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    public void validateCaMessage(String code) {
        if (!code.equals("9999")) {
            throw new ServiceException(MessageUtils.message("user.jcaptcha.error"));
        }
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 微信登录验证
     *
     * @param openId     微信唯一标识
     * @param sessionKey 微信会话密钥
     * @return 结果
     */
    public String wxLogin(String openId, String sessionKey) {
        WxUser JKUser = new WxUser();
        JKUser.setOpenid(openId);
        JKUser.setSessionKey(sessionKey);
        LoginUser loginUser = new LoginUser(JKUser);
        SysUser sysUser = new SysUser();
        sysUser.setUserName(openId);
        sysUser.setPassword(sessionKey);
        loginUser.setUser(sysUser);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(openId, sessionKey);
        authenticationToken.setDetails(loginUser);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 医生教职工小程序 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public Map<String, Object> ysLogin(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        UfZhgl ufZhgl = new UfZhgl();
        ufZhgl.setDlm(username);
        ufZhgl.setMm(password);
        List<UfZhgl> list = ufZhglService.selectUfZhglList(ufZhgl);
        //医生对象
        UfYsgl ufYsgl = new UfYsgl();
        //返回数据
        Map<String, Object> map = new HashMap<>();
        if (list.size() == 0) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        } else {
            if (list.get(0).getZhzt() == 1) {
                throw new ServiceException(MessageUtils.message("user.blocked"));
            }
            //医生端
            if (list.get(0).getZhlx() == JianKangConstant.YSZH) {
                ufYsgl = ufYsglService.selectUfYsglById(list.get(0).getGlId());
                //角色管理
                UfJsgl ufJsgl = new UfJsgl();
                String[] ids = ufYsgl.getYsjsId().split(",");
                ufJsgl.setRoleIds(ids);
                List<UfJsgl> roleYs = ufJsglService.listrole(ufJsgl);
                if (roleYs.size() > 0) {
                    for (int i = 0; i < roleYs.size(); i++) {
                        String[] menuids = roleYs.get(i).getXcxcd().split(",");
                        UfAppMenu ufAppMenu = new UfAppMenu();
                        ufAppMenu.setMenuids(menuids);
                        ufAppMenu.setMenuType(0L);
                        List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        ufAppMenu.setMenuType(1L);
                        List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                        roleYs.get(i).setUfAppMenu(listMenu);
                    }
                }
                map.put("jgName",ufYsgl.getSzjg());
                map.put("xm", ufYsgl.getYsxm());
                map.put("ysId", ufYsgl.getId().toString());
                map.put("username",ufZhgl.getDlm());
                map.put("jsInfo", roleYs);
                map.put("jgId",ufYsgl.getRequestId());
                map.put("roleType", JianKangConstant.YSD);

            }
            //教职工
            else {
                //教职工对象
                UfJzg ufJzg = new UfJzg();
                ufJzg = ufJzgService.selectUfJzgById(list.get(0).getGlId());
                List<UfJsgl> roleYs = ufJsglService.selectJzgRole(list.get(0).getId());
                if (roleYs.size() > 0) {
                    for (int i = 0; i < roleYs.size(); i++) {
                        String[] menuids = roleYs.get(i).getXcxcd().split(",");
                        UfAppMenu ufAppMenu = new UfAppMenu();
                        ufAppMenu.setMenuids(menuids);
                        ufAppMenu.setMenuType(0L);
                        List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        ufAppMenu.setMenuType(1L);
                        List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                        roleYs.get(i).setUfAppMenu(listMenu);
                    }
                }
                map.put("jgName",ufJzg.getSsdw());
                map.put("xm", ufJzg.getXm());
                map.put("ysId", ufJzg.getId().toString());
                map.put("username",ufJzg.getSjh());
                map.put("jsInfo", roleYs);
                map.put("roleType", JianKangConstant.JZG);
            }
        }
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(username);
        wxUser.setSessionKey(password);
        LoginUser loginUser = new LoginUser(wxUser);
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPassword(password);
        loginUser.setUser(sysUser);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        authenticationToken.setDetails(loginUser);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = tokenService.createToken(loginUser);
        map.put("token", token);
        map.put("id", list.get(0).getId().toString());

        // 生成token
        return map;
    }

    /**
     * 医生教职工小程序 切换角色
     *
     * @return 结果
     */
    public Map<String, Object> switchRole(Long id) {
        UfZhgl ufZhgl = ufZhglService.selectUfZhglById(id);
        //医生对象
        UfYsgl ufYsgl = new UfYsgl();
        //返回数据
        Map<String, Object> map = new HashMap<>();
        //医生端
        if (ufZhgl.getZhlx() == JianKangConstant.YSZH) {
            ufYsgl = ufYsglService.selectUfYsglById(ufZhgl.getGlId());
            //角色管理
            UfJsgl ufJsgl = new UfJsgl();
            String[] ids = ufYsgl.getYsjsId().split(",");
            ufJsgl.setRoleIds(ids);
            List<UfJsgl> roleYs = ufJsglService.listrole(ufJsgl);
            if (roleYs.size() > 0) {
                for (int i = 0; i < roleYs.size(); i++) {
                    String[] menuids = roleYs.get(i).getXcxcd().split(",");
                    UfAppMenu ufAppMenu = new UfAppMenu();
                    ufAppMenu.setMenuids(menuids);
                    ufAppMenu.setMenuType(0L);
                    List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                    ufAppMenu.setMenuType(1L);
                    List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                    roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                    roleYs.get(i).setUfAppMenu(listMenu);
                }
            }
            map.put("jgName",ufYsgl.getSzjg());
            map.put("jsInfo", roleYs);
        }else {
            List<UfJsgl> roleYs = ufJsglService.selectJzgRole(id);
            UfJzg ufJzg = ufJzgService.selectUfJzgById(ufZhgl.getGlId());
            if (roleYs.size() > 0) {
                for (int i = 0; i < roleYs.size(); i++) {
                    String[] menuids = roleYs.get(i).getXcxcd().split(",");
                    UfAppMenu ufAppMenu = new UfAppMenu();
                    ufAppMenu.setMenuids(menuids);
                    ufAppMenu.setMenuType(0L);
                    List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                    ufAppMenu.setMenuType(1L);
                    List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                    roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                    roleYs.get(i).setUfAppMenu(listMenu);
                }
            }
            map.put("jsInfo", roleYs);
            map.put("jgName",ufJzg.getSsdw());
        }
        // 生成token
        return map;
    }

    /**
     * 医生教职工小程序 登录验证
     *
     * @param username 用户名
     * @param code     验证码
     * @return 结果
     */
    public Map<String, Object> ysLoginPhone(String username, String code) {
        validateCaMessage(code);
        UfZhgl ufZhgl = new UfZhgl();
        ufZhgl.setDlm(username);
        List<UfZhgl> list = ufZhglService.selectUfZhglList(ufZhgl);
        //医生对象
        UfYsgl ufYsgl = new UfYsgl();
        //返回数据
        Map<String, Object> map = new HashMap<>();
        if (list.size() == 0) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        } else {
            if (list.get(0).getZhzt() == 1) {
                throw new ServiceException(MessageUtils.message("user.blocked"));
            }
            //医生端
            if (list.get(0).getZhlx() == JianKangConstant.YSZH) {
                ufYsgl = ufYsglService.selectUfYsglById(list.get(0).getGlId());
                //角色管理
                UfJsgl ufJsgl = new UfJsgl();
                String[] ids = ufYsgl.getYsjsId().split(",");
                ufJsgl.setRoleIds(ids);
                List<UfJsgl> roleYs = ufJsglService.listrole(ufJsgl);
                if (roleYs.size() > 0) {
                    for (int i = 0; i < roleYs.size(); i++) {
                        String[] menuids = roleYs.get(i).getXcxcd().split(",");
                        UfAppMenu ufAppMenu = new UfAppMenu();
                        ufAppMenu.setMenuids(menuids);
                        ufAppMenu.setMenuType(0L);
                        List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        ufAppMenu.setMenuType(1L);
                        List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                        roleYs.get(i).setUfAppMenu(listMenu);
                    }
                }
                map.put("jgName",ufYsgl.getSzjg());
                map.put("xm", ufYsgl.getYsxm());
                map.put("username",ufZhgl.getDlm());
                map.put("ysId", ufYsgl.getId().toString());
                map.put("jsInfo", roleYs);
                map.put("jgId",ufYsgl.getRequestId());
                map.put("roleType", JianKangConstant.YSD);
            }else {
                //教职工对象
                UfJzg ufJzg = new UfJzg();
                ufJzg = ufJzgService.selectUfJzgById(list.get(0).getGlId());
                List<UfJsgl> roleYs = ufJsglService.selectJzgRole(list.get(0).getId());
                if (roleYs.size() > 0) {
                    for (int i = 0; i < roleYs.size(); i++) {
                        String[] menuids = roleYs.get(i).getXcxcd().split(",");
                        UfAppMenu ufAppMenu = new UfAppMenu();
                        ufAppMenu.setMenuids(menuids);
                        ufAppMenu.setMenuType(0L);
                        List<UfAppMenu> listMenu = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        ufAppMenu.setMenuType(1L);
                        List<UfAppMenu> ufAppMenuButton = ufAppMenuService.selectUfAppMenuRoleList(ufAppMenu);
                        roleYs.get(i).setUfAppMenuButton(ufAppMenuButton);
                        roleYs.get(i).setUfAppMenu(listMenu);
                    }
                }
                map.put("jgName",ufJzg.getSsdw());
                map.put("xm", ufJzg.getXm());
                map.put("ysId", ufJzg.getId().toString());
                map.put("username",ufJzg.getSjh());
                map.put("jsInfo", roleYs);
                map.put("roleType", JianKangConstant.JZG);

            }
        }
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(username);
        wxUser.setSessionKey(code);
        LoginUser loginUser = new LoginUser(wxUser);
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPassword(code);
        loginUser.setUser(sysUser);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, code);
        authenticationToken.setDetails(loginUser);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = tokenService.createToken(loginUser);
        map.put("token", token);
        map.put("id", list.get(0).getId().toString());
        // 生成token
        return map;
    }

}
